package com.lyeducation.security.config;

import com.alibaba.fastjson.JSON;
import com.lyeducation.controllers.dto.system.SysUserDto;
import com.lyeducation.controllers.dto.system.userDetails.UserDetailsImpl;
import com.lyeducation.core.system.SysUserService;
import com.lyeducation.entities.system.SysUserEntity;
import com.lyeducation.security.SecurityConfig;
import com.lyeducation.util.jwt.JwtUtil;
import com.lyeducation.util.jwt.JwttokenconfigEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component("authenticationSuccessHandlerImpl")
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse,
            Authentication authentication)
            throws IOException, ServletException {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        UserDetailsImpl userDetails = null;
        SysUserEntity sysUserEntity = null;
        try {
            sysUserEntity = (SysUserEntity) SecurityPrincipalContext.getUserDetails();
//        sysUserEntity = sysUserRepository.setLoginUserRoleMenu(sysUserEntity);
//      paramMap.put("lastLoginIp", sysUserEntity.getLoginIp());
            userDetails = sysUserEntity.createUserDetailsImpl();
            SecurityConfig.setAuthenticationToSecurityContext(userDetails, httpServletRequest);
        } catch (Exception e) {
//      userDetails = SecurityPrincipalContext.getUserDetailsImpl();
        }

        sysUserService.updUserParamByLoginSuccess(httpServletRequest);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        paramMap.put(JwttokenconfigEnum.jti.getValue(), userDetails.getId());
        paramMap.put(JwttokenconfigEnum.sub.getValue(), userDetails.getName());
//    paramMap.put(SysConstants.PASSWORD.getValue(), userDetails.getPassword());
//    paramMap.put(JwttokenconfigEnum.roles.getValue(), userDetails.getAuthorities());
        String jwtToken = jwtUtil.generateToken(paramMap);
        jwtUtil.addJwtTokenToRedisHash(userDetails.getId(), jwtToken);

        StringBuffer sb = new StringBuffer(jwtUtil.getJwttokenconfigBean().getTokenHead());
        sb.append(jwtToken);
        String jwtHeader = sb.toString();
        httpServletResponse.setHeader(jwtUtil.getJwttokenconfigBean().getHeader(), jwtHeader);
        PrintWriter out = httpServletResponse.getWriter();
//    ObjectMapper objectMapper = new ObjectMapper();
        paramMap.clear();
        paramMap.put("status", "200");
        if (sysUserEntity != null) {
            SysUserDto sysUserDto = sysUserEntity.createSysUserDto();
            sysUserDto.setId(sysUserEntity.getId());
            paramMap.put("user", sysUserDto);

//      sb.append(  "{\"status\":\"success\",\"msg\":" + objectMapper.writeValueAsString(sysUserEntity.createSysUserDto()) + "}");
        }
        out.write(JSON.toJSONString(paramMap));
        out.flush();
        out.close();
    }
}
